import numpy as np
import pandas as pd
from functions.gra import gra_df

def get_df_similar_day(df_history, df_predict, day_size, similar_num):
    """day_size为每日的点数"""
    # 待预测日即为data中最后一天
    x_predict = np.array(df_predict.iloc[:, :-1]).flatten()
    days = int(len(df_history) // day_size)
    # 根据灰色关联系数生成相似日样本集
    lis = []
    for i in range(days):
        x = np.array(df_history.iloc[:, :-1][(days-i-1) * day_size : (days-i) * day_size]).flatten()
        y = np.array(df_history.iloc[:, -1:][(days-i-1) * day_size : (days-i) * day_size]).flatten()
        # 两列数求灰色关联系数
        da = pd.DataFrame({"origin": x_predict, "new": x})
        gra = gra_df(da).iloc[0, 1]
        dic = {"gra": gra, "x": x, "y": y, "day": i + 1}
        lis.append(dic)
    # 取相似度最高一天
    data = sorted(lis, key=lambda x: x["gra"])[-similar_num:]
    df_similar_day = []
    column_num = len(df_history.columns)
    for i in range(similar_num):
        # 将二维数组写入dataframe中
        df_data = data[i]["x"].reshape(len(data[i]["x"]) // (column_num-1), column_num-1)
        df = pd.DataFrame(df_data, columns=df_history.columns[:-1])
        df[df_history.columns[-1]] = data[i]["y"]
        df_similar_day.append(df)
    return df_similar_day
